﻿using IOT4Week1Day1.App;
using IOT4Week1Day1.App.Dtos;
using IOT4Week1Day1.Domain.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Common;
using IOT4Week1Day1.EFCore;
using Microsoft.EntityFrameworkCore; //引用efcore

namespace IOT4Week1Day1.ApiHost.Controllers
{
    /// <summary>
    /// 用户账号
    /// </summary>
    [Route("api/[controller]/[action]")]  //配置路由
    [ApiController]
    public class AccountController : ControllerBase
    {
        private readonly IUserAppService _userAppService;
        private readonly IAreaAppService _areaAppService;

        private readonly MyDbContext _db;
        public AccountController(IUserAppService userAppService, IAreaAppService areaAppService, MyDbContext db)
        {
            _userAppService = userAppService;
            _areaAppService = areaAppService;
            _db = db;
        }

        /// <summary>
        /// 登录接口
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Login(LoginDto input)
        {
            //1. 用户输入的验证码与redis缓存中的验证码进行比较
            string strCode = HttpContext.Session.GetString("vcode");

            if (!input.CaptchaCode.Equals(strCode))
            {
                return Ok(new { msg = "验证码无效", result = -1 });
            }

            //2. 查询用户输入的账号密码在数据库中是否存在
            //调用
            User user = _userAppService.Login(input);
            if (user != null)
            {
                return Ok(new { msg = "登录成功", result = 1, data = user });
            }

            return Ok(new { msg = "登录失败", result = 0 });

        }

        /// <summary>
        /// 获取图片验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetVCode()
        {
            //1. 生成图片验证码（用到帮助类）
            ValidateCodeHelper helper = new ValidateCodeHelper();

            var ms = helper.Create(out string code, 5); //生成图片验证码，5位的

            //2. 设置到session缓存
            HttpContext.Session.SetString("vcode", code);

            //3. 返回图片
            return File(ms.ToArray(), "image/png");
        }

        /// <summary>
        /// 批量逻辑删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Delete(List<int> ids)
        {
            //int result = _userAppService.Delete(ids);

            string strIds = string.Join(',', ids);
            string strSql = $"delete from Users where UId in ({strIds})"; //物理删除
            string strSql2 = $"update Users set IsDeleted=1 where UId in ({strIds})"; //逻辑删除
            int result = _db.Database.ExecuteSqlRaw(strSql2);

            return Ok(new { msg = result > 0 ? "删除成功！" : "删除失败", result });
        }

        /// <summary>
        /// 获取地区层级数据（树形）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAreaList()
        {
            var data = _areaAppService.GetAreaTree();

            return Ok(new { msg = "地区树形数据加载成功", data });
        }


        /// <summary>
        /// 获取用户分页数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetUserList(int pageIndex=1, int pageSize=2, string name="", bool? status=null)
        {
            PagedList<User> result = _userAppService.GetPage(pageIndex, pageSize, name, status);

            return Ok(new { data=result.PagedData, totalCount=result.TotalCount });
        }


        /// <summary>
        /// 返填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Get(int id)
        {
            return  Ok(_userAppService.Get(id));
        }

        /// <summary>
        /// 修改功能
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Update(User input)
        {
            //为什么前端做了验证，后端还要做验证呢？
            if (!ModelState.IsValid)
            {
                return Ok(new { msg = "无效数据", result=-1 });
            }

            int result = _userAppService.UpdateUser(input);

            return Ok(new { msg = result > 0 ? "修改成功" : "修改失败", result });
            
        }

    }
}
